package reentrereadlockDemo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/***
 * 读写锁
 *
 * 读读并发
 * 读写互斥
 * 写写互斥
 */
public class TestDemo {

    public static void main(String[] args) {
        ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.ReadLock readLock = rwl.readLock();
        ReentrantReadWriteLock.WriteLock writeLock = rwl.writeLock();

//        new Thread(new Runnable() {
//            public void run() {
//
//                readLock.lock();
//                System.out.println("Thread-1 获取读锁");
//                try {
//                    for (int i = 0; i < 10; i++) {
//                        m1(i);
//                    }
//                } finally {
//                    readLock.unlock();
//                }
//            }
//        }, "Thread-1").start();
//        new Thread(new Runnable() {
//            public void run() {
//                writeLock.lock();
//                System.out.println("Thread-2 获取写锁");
//                try {
//                    for (int i = 0; i < 20; i++) {
//                        m1(i);
//                    }
//                } finally {
//                    writeLock.unlock();
//                }
//            }
//        }, "Thread-2").start();

        new Thread(new Runnable() {
            public void run() {
                readLock.lock();
                System.out.println("获取读锁");
                writeLock.lock();
                System.out.println("获取写锁");
            }
        }).start();



    }

    static void  m1(int val){
        System.out.println("执行："+val+" Thread.name="+Thread.currentThread().getName());
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
